'use client'
import * as React from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { cn } from '@/lib/utils'
import { buttonVariants } from '@/components/ui/button'
import { PanelLeft, Inbox, Ear, MessagesSquare, MessageSquareReply, CreditCard, LogOut } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { Card, CardHeader, CardContent } from '@/components/ui/card'
import { Progress } from '@/components/ui/progress'
import { Sheet, SheetContent, SheetTrigger, SheetClose } from '@/components/ui/sheet'
import { Toaster } from '@/components/ui/toaster'
import DashboardBreadcrumb from '@/components/DashbordBreadcrumb'
import ProjectSwitcher from '@/components/ProjectSwitcher'
import UpgradeAlert from '@/components/UpgradeAlert'
import { useSelector, useDispatch } from 'react-redux'
import { setUser } from '@/store/user-slice'
import { setCurProject } from '@/store/project-slice'
import { selectConfig, setConfig } from '@/store/config-slice'
import useRequest from '@/utils/request'

const menus = [
  {
    title: 'Projects',
    icon: Inbox,
    path: '/projects',
  },
  {
    title: 'Keywords',
    icon: Ear,
    path: '/keywords',
  },
  {
    title: 'Mentions',
    icon: MessagesSquare,
    path: '/mentions',
  },
  {
    title: 'Replies',
    icon: MessageSquareReply,
    path: '/replies',
  },
  {
    title: 'Blilling',
    icon: CreditCard,
    path: '/billing',
  },
]

export default function Dashboard({ children }) {
  const [isCollapsed, setIsCollapsed] = React.useState(false)
  const dispatch = useDispatch()
  const config = useSelector(selectConfig)
  const request = useRequest()
  const pathname = usePathname()
  const router = useRouter()

  const handleLogout = async () => {
    router.push('/')

    setTimeout(() => {
      dispatch(setUser(null))
      dispatch(setCurProject(null))
    }, 1000)
  }

  React.useEffect(() => {
    const fetchConfig = async () => {
      const res = await request.get('account/config')

      dispatch(setConfig(res.data))
    }

    fetchConfig()
  }, [])

  return (
    <div className="flex min-h-screen w-full flex-col bg-muted/40">
      <aside className="fixed inset-y-0 left-0 z-10 hidden w-[240px] flex-col border-r bg-background sm:flex">
        <div className="flex h-14 items-center border-b px-4 lg:h-[60px] lg:px-6">
          <div className="flex items-center justify-center gap-2 font-semibold">
            <span className="">RedGrowth</span>
          </div>
        </div>
        <div className={cn('flex h-[52px] items-center justify-center mt-2', isCollapsed ? 'h-[52px]' : 'px-2')}>
          <ProjectSwitcher isCollapsed={isCollapsed} />
        </div>
        <div
          data-collapsed={isCollapsed}
          className="group flex flex-col gap-4 py-2 data-[collapsed=true]:py-2 h-full max-h-screen"
        >
          <div className="flex-1">
            <nav className="grid gap-1 px-2 group-[[data-collapsed=true]]:justify-center group-[[data-collapsed=true]]:px-2">
              {menus.map((menu, index) =>
                isCollapsed ? (
                  <Tooltip key={index} delayDuration={0}>
                    <TooltipTrigger asChild>
                      <Link
                        href="#"
                        className={cn(
                          buttonVariants({ variant: menu.variant, size: 'icon' }),
                          'h-9 w-9',
                          menu.variant === 'default' &&
                            'dark:bg-muted dark:text-muted-foreground dark:hover:bg-muted dark:hover:text-white'
                        )}
                      >
                        <menu.icon className="h-4 w-4" />
                        <span className="sr-only">{menu.title}</span>
                      </Link>
                    </TooltipTrigger>
                    <TooltipContent side="right" className="flex items-center gap-4">
                      {menu.title}
                      {menu.label && <span className="ml-auto text-muted-foreground">{menu.label}</span>}
                    </TooltipContent>
                  </Tooltip>
                ) : (
                  <Link
                    key={index}
                    href={menu.path}
                    className={cn(
                      buttonVariants({ variant: pathname.startsWith(menu.path) ? 'default' : 'ghost', size: 'sm' }),
                      pathname.startsWith(menu.path) &&
                        'dark:bg-muted dark:text-white dark:hover:bg-muted dark:hover:text-white',
                      'justify-start'
                    )}
                  >
                    <menu.icon className="mr-2 h-4 w-4" />
                    {menu.title}
                    {menu.label && (
                      <span
                        className={cn('ml-auto', pathname.startsWith(menu.path) && 'text-background dark:text-white')}
                      >
                        {menu.label}
                      </span>
                    )}
                  </Link>
                )
              )}
            </nav>
          </div>
          {config.reply !== '--' && (
            <div className="mt-auto p-2">
              <Card>
                <CardHeader>
                  <div className="flex place-content-between">
                    <div>Replies</div>
                    <div>
                      {config.redgrowth_config.reply - config.reply}/{config.redgrowth_config.reply}
                    </div>
                  </div>
                  <Progress
                    value={((config.redgrowth_config.reply - config.reply) / config.redgrowth_config.reply) * 100}
                  />
                  <div className="flex place-content-between">
                    <p>Keywords</p>
                    <p>
                      {config.redgrowth_config.keyword - config.keyword}/{config.redgrowth_config.keyword}
                    </p>
                  </div>
                  <Progress
                    value={((config.redgrowth_config.keyword - config.keyword) / config.redgrowth_config.keyword) * 100}
                  />
                </CardHeader>
                <CardContent>
                  <Link href={'/billing'}>
                    <Button size="sm" className="w-full" onClick={() => close(false)}>
                      Upgrade
                    </Button>
                  </Link>
                </CardContent>
              </Card>
            </div>
          )}
        </div>
      </aside>
      <div className="flex flex-col sm:gap-4 sm:py-4 sm:pl-[240px]">
        <header className="sticky top-0 z-30 flex h-14 items-center gap-4 border-b bg-background px-4 sm:static sm:h-auto sm:border-0 sm:bg-transparent sm:px-6">
          <Sheet>
            <SheetTrigger asChild>
              <Button size="icon" variant="outline" className="sm:hidden">
                <PanelLeft className="h-5 w-5" />
                <span className="sr-only">Toggle Menu</span>
              </Button>
            </SheetTrigger>
            <SheetContent side="left" className="sm:max-w-xs">
              <nav className="grid gap-6 text-lg font-medium">
                <Link href="/" className="flex items-center justify-start gap-2 font-semibold">
                  <span className="">RedGrowth</span>
                </Link>
                <div className={cn('flex h-[52px] items-center justify-center', isCollapsed ? 'h-[52px]' : 'px-2')}>
                  <ProjectSwitcher isCollapsed={isCollapsed} />
                </div>
                {menus.map((menu, index) => (
                  <SheetClose key={index} asChild>
                    <Link
                      href={menu.path}
                      className={cn(
                        buttonVariants({
                          variant: pathname.startsWith(menu.path) ? 'default' : 'ghost',
                          size: 'sm',
                        }),
                        pathname.startsWith(menu.path) &&
                          'dark:bg-muted dark:text-white dark:hover:bg-muted dark:hover:text-white',
                        'justify-start'
                      )}
                    >
                      <menu.icon className="mr-2 h-5 w-5" />
                      {menu.title}
                    </Link>
                  </SheetClose>
                ))}
              </nav>
              {config.reply !== '--' && (
                <div className="mt-4">
                  <Card>
                    <CardHeader>
                      <div className="flex place-content-between">
                        <div>Replies</div>
                        <div>
                          {config.redgrowth_config.reply - config.reply}/{config.redgrowth_config.reply}
                        </div>
                      </div>
                      <Progress
                        value={((config.redgrowth_config.reply - config.reply) / config.redgrowth_config.reply) * 100}
                      />
                      <div className="flex place-content-between">
                        <p>Keywords</p>
                        <p>
                          {config.redgrowth_config.keyword - config.keyword}/{config.redgrowth_config.keyword}
                        </p>
                      </div>
                      <Progress
                        value={
                          ((config.redgrowth_config.keyword - config.keyword) / config.redgrowth_config.keyword) * 100
                        }
                      />
                    </CardHeader>
                    <CardContent>
                      <Link href={'/billing'}>
                        <SheetClose className="w-[100%]">
                          <Button size="sm" className="w-full" onClick={() => close(false)}>
                            Upgrade
                          </Button>
                        </SheetClose>
                      </Link>
                    </CardContent>
                  </Card>
                </div>
              )}
            </SheetContent>
          </Sheet>
          <DashboardBreadcrumb />
          <div className="relative ml-auto flex-1 md:grow-0">
            {/* <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
            <Input
              type="search"
              placeholder="Search..."
              className="w-full rounded-lg bg-background pl-8 md:w-[200px] lg:w-[336px]"
            /> */}
          </div>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="outline" size="icon" className="overflow-hidden rounded-full">
                <Image
                  src="/placeholder-user.jpg"
                  width={36}
                  height={36}
                  alt="Avatar"
                  className="overflow-hidden rounded-full"
                />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {/* <DropdownMenuLabel>My Account</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem>Settings</DropdownMenuItem>
              <DropdownMenuItem>Support</DropdownMenuItem>
              <DropdownMenuSeparator /> */}
              <DropdownMenuItem
                onSelect={() => {
                  handleLogout()
                }}
              >
                <LogOut className="mr-2 h-4 w-4" />
                <span>Log out</span>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </header>
        <main className="grid flex-1 items-start gap-4 p-4 sm:px-6 sm:py-0 md:gap-4">
          {config.reply <= 0 && <UpgradeAlert />}
          {children}
        </main>
      </div>
      <Toaster />
    </div>
  )
}
